﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using AlipaySDK.Dto.BizModel;
using Common.Logging;
using OutDbContext;
using User.Api.Helpers;


namespace User.Api.Models
{
    /// <summary>
    /// 自定义MessageHandler
    /// </summary> 
    public partial class AliMessageHandler
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(AliMessageHandler));
        private static readonly string BaseAddress = ConfigurationManager.AppSettings["BaseAddress"];
        public string GetWelcomeInfo()
        {
            //https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2015052700092241&auth_skip=false&scope=auth_base&redirect_uri=http://wx.e3861.com/Alipay/WxMembers/Redirect?rUrl=http://wx.e3861.com/Alipay/WxHosp/Home
            var homeUrl = MessageHelper.GetH5Url("");
            var info = $"欢迎关注广东省妇幼保健院支付宝服务窗。请使用下方菜单来操作您需要的服务。也可以直接进入我们的<a href=\"{homeUrl}\">微网站</a>，来使用我们的服务哦！";

            return info;
        }


        /// <summary>
        /// 扫描二维码绑卡，用户已关注服务窗时，调用此方法
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public string OnEvent_ScanRequest(string eventkey, string openId)
        {
            var responseMessageContent = "";
            HospCard card = null;
            var resultCode = CardService.BindCardByScan(eventkey.ToLongOrDefault(), openId, out card);
            if (resultCode == 1)//超出最大绑卡数量
            {
                responseMessageContent = "绑卡失败，原因：超出最大绑卡数量。\r\n如需帮助，请与客服联系。";
            }
            else if (resultCode == 2)
            {
                responseMessageContent = "您已经添加过此就诊卡，请不要重复添加。\r\n如需帮助，请与客服联系。";
            }
            else if (resultCode == 0) //绑卡成功
            {
                if (card != null)
                {
                    var patientName = card.PatientName;
                    var cardType = card.CardType == 0
                        ? "诊疗卡"
                        : card.CardType == 1 ? "健康卡" : card.CardType == 2 ? "市民卡" : "";
                    var cardNo = card.CardNo;
                    var sb = new StringBuilder();
                    sb.Append("扫描二维码绑卡成功。您的就诊卡信息如下：\r\n");
                    sb.AppendFormat("姓名：{0}", patientName).Append("\r\n");
                    sb.AppendFormat("卡号：{0}", cardNo).Append("\r\n");
                    sb.AppendFormat("卡类型：{0}", cardType).Append("\r\n");
                    responseMessageContent = sb.ToString();
                }
            }

            return responseMessageContent;
        }

        /// <summary>
        /// 语音或文字处理
        /// </summary>
        /// <param name="message"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        internal string ProcessMessage(string message,string openId)
        {
            var recognition = message;
            if (recognition.Contains("预约"))
            {
                return GetWxAppt(openId);
            }
            else if (recognition.Contains("挂号单"))
            {
                return GetReport(openId);
            }
            else if (recognition.Contains("挂号"))
            {
                return GetWxAppt(openId);
            }
            else if (recognition.Contains("取号"))
            {
                return GetOtherAppt(openId);
            }
            else if (recognition.Contains("号"))
            {
                return GetOtherAppt(openId);
            }
            else if (recognition.Contains("候诊") || recognition.Contains("队列") || recognition.Contains("排队"))
            {
                return GetQueue(openId);
            }
            else if (recognition.Contains("检验"))
            {
                return GetHealthReport(openId);
            }
            else if (recognition.Contains("检查"))
            {
                return GetHealthReport(openId);
            }
            else if (recognition.Contains("报告"))
            {
                return GetHealthReport(openId);
            }
            else if (recognition.Contains("缴费") || recognition.Contains("交费") || recognition.Contains("费"))
            {
                return GetBill(openId);
            }
            else if (recognition.Contains("就诊卡") || recognition.Contains("卡"))
            {
                return GetCard(openId);
            }
            else if (recognition.Contains("满意"))
            {
                return GetServiceSIPaper(openId);
            }
            else if (recognition.Contains("住院"))
            {
                return GetInpatientHistory(openId);
            }
            else if (recognition.Contains("订餐"))
            {
                return GetDinnerInfo(openId);
            }
            else if (recognition.Contains("知识"))
            {
                return GetEducationInfo(openId);
            }
            else if (recognition.Contains("咨询"))
            {
                return GetConsultationInfo(openId);
            }
            else
            {
               return "很抱歉！我理解不了你的话语";  
            }
        }

        /// <summary>
        /// 在线取号
        /// </summary>
        /// <returns></returns>
        public string GetOtherAppt(string wxOpenId)
        {
            var result = new StringBuilder();

            var description = @"在线取号说明
1.在其他平台（官网、电话）预约，使用本院诊疗卡预约的取号以及医生诊间加号的取号。
2.如因您自身原因迟到，系统将自动安排您在本班次最后就诊或者退号重新现场挂号。";
            //4.如需退预约号，请于支付当天晚12点前办理，超时请在就诊日期前移步就诊院区的人工窗口办理。";

            var url = MessageHelper.GetH5Url("/index/get-other-appt");

            result.Append(description).Append("\r\n\r\n"); ;
            result.AppendFormat("<a href=\"{0}\">点这里【在线取号】</a>", url);
            return result.ToString();
        }

        /// <summary>
        /// 订阅（关注）事件。通过“EventKey”来区分用户是否是从带场景值的二维码来关注，如是，自动给用户绑定卡信息
        /// </summary>
        /// <returns></returns>
        public string OnEvent_SubscribeRequest(string openId, string eventkey)
        {
            var now = DateTime.Now;
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var user = ctx.WxUsers.FirstOrDefault(p => p.OpenId == openId);
                if (user != null)
                {
                    user.SubscribeDt = now;
                    user.UnsubscribeDt = null;
                    user.LastActiveDt = now;
                    user.RecStatus = 1;
                    ctx.SaveChanges();
                }
                else
                {
                    user = new OutDbContext.WxUser
                    {
                        OpenId = openId,
                        SubscribeDt = now,
                        LastActiveDt = now,
                        IsBkMember = 0,
                        RecStatus = 1,
                        RecCreateDt = now
                    };
                    ctx.WxUsers.Add(user);
                    ctx.SaveChanges();
                }
            }

            var responseMessageContent = "";

            if (string.IsNullOrEmpty(eventkey))
            {
                responseMessageContent = GetWelcomeInfo();
            }
            else
            {
                responseMessageContent = GetWelcomeInfo();

                HospCard card = null;
                var resultCode = CardService.BindCardByScan(eventkey.ToLongOrDefault(), openId, out card);
                if (resultCode == 1)//超出最大绑卡数量
                {
                    responseMessageContent += "\r\n\r\n" + "扫描二维码绑卡失败，原因：超出最大绑卡数量。\r\n如需帮助，请与客服联系。";
                }
                else if (resultCode == 2)
                {
                    responseMessageContent += "\r\n\r\n" + "您已经添加过此就诊卡，请不要重复添加。\r\n如需帮助，请与客服联系。";
                }
                else if (resultCode == 0)//绑卡成功
                {
                    if (card != null)
                    {
                        var patientName = card.PatientName;
                        var cardType = card.CardType == 0 ? "诊疗卡" : card.CardType == 1 ? "健康卡" : card.CardType == 2 ? "市民卡" : "";
                        var cardNo = card.CardNo;
                        var sb = new StringBuilder();
                        sb.Append("扫描二维码绑卡成功。您的就诊卡信息如下：\r\n");
                        sb.AppendFormat("姓名：{0}", patientName).Append("\r\n");
                        sb.AppendFormat("卡号：{0}", cardNo).Append("\r\n");
                        sb.AppendFormat("卡类型：{0}", cardType).Append("\r\n");

                        responseMessageContent += "\r\n\r\n" + sb.ToString();
                    }
                }
            }

            return responseMessageContent;

        }



        /// <summary>
        /// 退订
        /// 实际上用户无法收到非订阅账号的消息，所以这里可以随便写。
        /// unsubscribe事件的意义在于及时删除网站应用中已经记录的OpenID绑定，消除冗余数据。并且关注用户流失的情况。
        /// </summary>
        /// <returns></returns>
        public  string OnEvent_UnsubscribeRequest(string openId)
        {
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var user = ctx.WxUsers.FirstOrDefault(p => p.OpenId == openId);
                if (user != null)
                {
                    var now = DateTime.Now;
                    user.UnsubscribeDt = now;
                    user.LastActiveDt = now;
                    ctx.SaveChanges();
                }
            }

            return "有空再来";
             
        }

        public List<SendPhotoBizContent.Article> GetHospitalInfo(string wxOpenId)
        {
            var sendarticles = new List<SendPhotoBizContent.Article>();

            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "广东省妇幼保健院",
                title = "广东省妇幼保健院",
                desc = "三级甲等",
                imageUrl = BaseAddress + "/Images/PanYuBranch.jpg",
                url = MessageHelper.GetH5Url("/index/portal")
            });
            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "番禺院区",
                title = "番禺院区",
                desc = "",
                imageUrl = "",
                url = MessageHelper.GetH5Url("/index/branch-panyu")
            });
            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "越秀院区",
                title = "广东省妇幼保健院",
                desc = "",
                imageUrl = "",
                url = MessageHelper.GetH5Url("/index/branch-yuexiu")
            });
            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "海珠院区",
                title = "海珠院区",
                desc = "",
                imageUrl = "",
                url = MessageHelper.GetH5Url("/index/branch-haizhu")
            });

            return sendarticles;
        }

        public List<SendPhotoBizContent.Article> GetDepartmentInfo(string wxOpenId)
        {
            var sendarticles = new List<SendPhotoBizContent.Article>();

            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "科室介绍",
                title = "科室介绍",
                desc = "",
                imageUrl = BaseAddress + "/Images/ksjs.jpg",
                url = MessageHelper.GetH5Url("/index/depart-list?branchName=panyu&purpose=detail")
            });

            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "番禺院区",
                title = "番禺院区",
                desc = "",
                imageUrl = "",
                url = MessageHelper.GetH5Url("/index/depart-list?branchName=panyu&purpose=detail")
            });
            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "越秀院区",
                title = "越秀院区",
                desc = "",
                imageUrl = "",
                url = MessageHelper.GetH5Url("/index/depart-list?branchName=yuexiu&purpose=detail")
            });
            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "海珠院区",
                title = "海珠院区",
                desc = "",
                imageUrl = "",
                url = MessageHelper.GetH5Url("/index/depart-list?branchName=haizhu&purpose=detail")
            });

            return sendarticles;
        }

        public List<SendPhotoBizContent.Article> GetDoctorInfo(string wxOpenId)
        {
            var sendarticles = new List<SendPhotoBizContent.Article>();

            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "医生介绍",
                title = "医生介绍",
                desc = "",
                imageUrl = BaseAddress + "/Images/ysjs.jpg",
                url = ""
            });

            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "番禺院区",
                desc = "",
                imageUrl = "",
                url = ""
            });
            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "越秀院区",
                desc = "",
                imageUrl = "",
                url = ""
            });
            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "海珠院区",
                desc = "",
                imageUrl = "",
                url = ""
            });

            return sendarticles;
        }


        /// <summary>
        /// 在线挂号
        /// </summary>
        /// <returns></returns>
        public string GetWxAppt(string wxOpenId)
        {

            var result = new StringBuilder();

            var description = @"在线挂号说明
1.您可挂当天或预约一周之内的医生号源。
2.挂号需绑定本院诊疗卡。
3.挂号支付成功后，请查阅“电子挂号单”，到指定诊室外等候呼叫、就诊。
4.如需退号，请凭“电子挂号单”到各楼层挂号处办理。
5.微信支付暂不支持退伍军人、老人、残疾人等减免政策。";

            var guaHaoUrl = MessageHelper.GetH5Url("/index/depart-list?branchName=panyu&purpose=appt");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【在线挂号】</a>", guaHaoUrl).Append("\r\n");

            return result.ToString();
        }

        public string GetTestInfo(string wxOpenId)
        {
            var result = new StringBuilder();

            var description = "测试";

            //string getNoUrl = GetRedirectUrl("WxCard", "DaiKou", wxOpenId);

            //result.Append(description).Append("\r\n\r\n");
            //result.AppendFormat("<a href=\"{0}\">点这里【代扣协议】</a>", getNoUrl).Append("\r\n\r\n\r\n");


            return result.ToString();

        }


        /// <summary>
        /// 候诊队列
        /// </summary>
        /// <returns></returns>
        public string GetQueue(string wxOpenId)
        {

            var result = new StringBuilder();

            var description = @"候诊队列说明
1.候诊队列支持实时查询候诊信息，可能因网络延时等原因造成信息不一致，微信查询仅供参考，请以现场候诊队列信息为准。";

            var url = MessageHelper.GetH5Url("/index/get-queue");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里查看【候诊队列】</a>", url).Append("\r\n");

            return result.ToString();
        }



        /// <summary>
        /// 就诊缴费
        /// </summary>
        /// <returns></returns>
        public string GetBill(string wxOpenId)
        {

            var result = new StringBuilder();

            var description = @"就诊缴费说明
1.缴费提供微信支付。
2.处方单当天缴费有效。
3.目前微信支付只提供自费病人缴费，普通门诊医保统筹记账缴费（仅开通妇科门诊医保自助缴费，自付部分按自费缴费）、门慢医保、门特医保、公费医疗在微信支付按自费缴费，如需记账请移步到各楼层收费窗口进行缴费。
4.如需打印发票或办理退费请凭微信缴费“电子凭条”到各楼层收费处办理。
5.如需打印费用清单请凭发票到前线服务打印。";

            var url = MessageHelper.GetH5Url("/index/get-bill");

            result.Append(description).Append("\r\n\r\n"); ;
            result.AppendFormat("<a href=\"{0}\">点这里【就诊缴费】</a>", url).Append("\r\n");

            return result.ToString(); ;
        }


        /// <summary>
        /// 取报告单
        /// </summary>
        /// <returns></returns>
        public string GetHealthReport(string wxOpenId)
        {
            var result = new StringBuilder();

            var description = @"报告单说明
1.默认可以查询一个月的检查/检验单。
2.可以筛选自开始日期起10天内的检查/检验单。
3.本检查单/检验单仅供参考。
4.若有需要请到医院提取纸质报告单或使用自助机打印。";

            var checkUrl = MessageHelper.GetH5Url("/index/get-check");
            var inspectionUrl = MessageHelper.GetH5Url("/index/get-inspection");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【取检查单】</a>", checkUrl).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【取检验单】</a>", inspectionUrl).Append("\r\n");


            return result.ToString(); ;
        }



        /// <summary>
        /// 我的单据
        /// </summary>
        /// <returns></returns>
        public string GetReport(string wxOpenId)
        {
            var result = new StringBuilder();

            var description = @"我的单据说明
1. 挂号单：可以查询此微信号缴过的挂号单明细信息。
2. 缴费单： 可以查询此微信号缴过的缴费单明细信息。
3. 预交金单：可以查询此微信号交过的预交金单信息。
";

            var apptRegOrderUrl = MessageHelper.GetH5Url("/index/reg-order-list");
            var paidBillUrl = MessageHelper.GetH5Url("/index/bill-order-list");
            var inpatientPrepayUrl = MessageHelper.GetH5Url("/index/prepay-order-list");
            var dinnerUrl = MessageHelper.GetH5Url("/index/dinner-order-list");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【查询挂号单】</a>", apptRegOrderUrl).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【查询缴费单】</a>", paidBillUrl).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【查询住院预交金记录】</a>", inpatientPrepayUrl).Append("\r\n\r\n");


            return result.ToString(); ;
        }



        /// <summary>
        /// 我的就诊卡
        /// </summary>
        /// <returns></returns>
        public string GetCard(string wxOpenId)
        {

            var result = new StringBuilder();

            var description = @"我的就诊卡说明
以下情况可在“管理就诊卡”进行绑定
1.有我院诊疗卡
2.有广州市健康卡并且已绑定我院就诊卡
除此之外，如还无诊疗卡可以在“管理就诊卡”进行初诊建卡或到我院门诊一楼前线服务，办理诊疗卡或广州市健康卡。";

            var url = MessageHelper.GetH5Url("/index/manage-card");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里【管理就诊卡】</a>", url).Append("\r\n"); ;

            return result.ToString();
        }


         /// <summary>
        /// 服务说明
        /// </summary>
        /// <returns></returns>
        public string GetServiceDescription(string wxOpenId)
        {
            var result = new StringBuilder();

            var description = @"";

            var url = MessageHelper.GetH5Url("/index/hosp-service-desc");

            result.Append(description).Append("");
            result.AppendFormat("<a href=\"{0}\">点这里查看【服务说明】</a>", url).Append("\r\n"); ;

            return result.ToString(); ;
        }

        /// <summary>
        /// 服务说明
        /// </summary>
        /// <returns></returns>
        public string GetServiceSIPaper(string wxOpenId)
        {
            var result = new StringBuilder();

            var description = @"";

            var url = MessageHelper.GetH5Url("/index/paper-list");

            result.Append(description).Append("");
            result.AppendFormat("<a href=\"{0}\">点这里【满意度调查】</a>", url).Append("\r\n");

            return result.ToString(); ;
        }

        /// <summary>
        /// 医院公告
        /// </summary>
        /// <returns></returns>
        public List<SendPhotoBizContent.Article> GetHospNoticeInfo(string wxOpenId)
        {

            var sendarticles = new List<SendPhotoBizContent.Article>();

            sendarticles.Add(new SendPhotoBizContent.Article()
            {
                actionName = "医院公告",
                title = "医院公告",
                desc = "",
                imageUrl = "",
                url = ""
            });

            List<Notice> noticeList;
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                noticeList = ctx.Notices.Where(x => x.RecStatus == 1)
                                .OrderBy(x => x.Sort)
                                .ThenBy(x => x.RecCreateDt)
                                .Take(5)
                                .ToList();
            }

            foreach (var notice in noticeList)
            {
                sendarticles.Add(new SendPhotoBizContent.Article()
                {
                    actionName = notice.Title,
                    title = notice.Title,
                    desc = "",
                    imageUrl = "",
                    url = ""
                });
            }

            return sendarticles;
        }


        /// <summary>
        /// 住院历史信息
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public string  GetInpatientHistory(string wxOpenId)
        {

            var result = new StringBuilder();

            var description = @"服务说明：
1、住院每日清单查询。
2、住院预交金充值。";
            //3、查询住院报告。";

            var url = MessageHelper.GetH5Url("/index/get-inpatient"); ;

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里办理【住院服务】</a>", url).Append("\r\n");

            return result.ToString();

        }

        /// <summary>
        /// 订餐信息
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public string GetDinnerInfo(string wxOpenId)
        {

            var result = new StringBuilder();

            var description = @"订餐服务说明：

1.微信订餐只有住院病人才能使用，目前微信订餐服务处于测试阶段，只针对一部分科室开放，如果打开点餐页面没有看到“去订餐”的按纽，说明您所在的科室还未开放微信订餐；
2.订餐时需要通过微信支付餐费，不通过饭卡扣费；
3.订餐成功后工作人员会在相应的时间送餐至您的床前。";

            var url = MessageHelper.GetH5Url("/index/do-dinner");

            result.Append(description).Append("\r\n\r\n");
            result.AppendFormat("<a href=\"{0}\">点这里办理【订餐服务】</a>", url).Append("\r\n");

            return  result.ToString();
        }

        /// <summary>
        /// 宣教知识信息
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public string GetEducationInfo(string wxOpenId)
        {
            var result = new StringBuilder();

            var url = MessageHelper.GetH5Url("/index/education-type");

            result.AppendFormat("<a href=\"{0}\">点这里查看【宣教知识】</a>", url).Append("\r\n");

            return result.ToString();
        }
        /// <summary>
        /// 在线咨询
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public string GetConsultationInfo(string wxOpenId)
        {
            var result = new StringBuilder();
            var url = "";
            result.AppendFormat("<a href=\"{0}\">点这里【在线咨询】</a>", url).Append("\r\n\r\n");

            return result.ToString();
        }


        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        public string GetNewWeixin(string wxOpenId)
        {
            var result = new StringBuilder();
            var url = @"https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2015052700092241&auth_skip=false&scope=auth_userinfo&state={WxOauth2State}&redirect_uri=http://wx.e3861.com/api/Auth/WxOauth2?url=http://wx.e3861.com/h5/index.html#!/index/portal";

            result.AppendFormat("<a href=\"{0}\">点这里【XINWEIXIN】</a>", url).Append("\r\n\r\n");

            return result.ToString();
        }

    }
}